import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../layout/Home.vue'
import Dash from '../views/Dashboard'
import local from '@/utils/local.js'
import StaticRoutes from './staticRoute'
import _ from 'lodash'

Vue.use(VueRouter)

// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      // 后台首页
      {
        path: '/',
        component: Dash
      }
    ]
  },
  {
    path: '/login',
    component: () =>
      import(/* webpackChunkName: "login" */ '../views/Login.vue')
  },
  {
    path: '/404',
    component: () =>
      import(/* webpackChunkName: "error" */ '../views/Error.vue')
  },
  {
    path: '*',
    // 重定向
    redirect: '/404'
  }
]

// component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

const router = new VueRouter({
  routes
})

// 计算路由的信息
calcRoute()
export function calcRoute() {
  const role = local.get('role')
  if (!role) return ''

  // 根据上面定义的一大堆规则，进行筛选和过滤
  const lastArr = filterRouter(StaticRoutes.children, role)
  // console.log(lastArr)
  // 爆炸重要!!!!   addRoute   添加的是一个对象   addRoutes  添加的是数组
  StaticRoutes.children = lastArr
  router.addRoute(StaticRoutes)

  // 根据计算出来的数组，过滤将来要去遍历的导航数组
  const lastMenu = filterMenu(_.cloneDeep(lastArr))
  // console.log(lastMenu, 123)
  local.set('menus', JSON.stringify(lastMenu))
}

// 定义一个过滤导航的方法
function filterMenu(arr) {
  return arr.filter(item => {
    if (!item.hidden) {
      if (item.children) {
        item.children = filterMenu(item.children)
      }
      return true
    } else {
      return false
    }
  })
}

// 定义一个过滤的方法计算路由
function filterRouter(arr, role) {
  return arr.filter(item => {
    // return true  留下，  return  false  不留下
    if (item.meta && item.meta.role) {
      if (item.meta.role.includes(role)) {
        // 如果还有子路由，就继续递归进行过滤
        if (item.children) {
          item.children = filterRouter(item.children, role)
        }
        return true
      } else {
        return false
      }
      // 递归
    } else {
      return true
    }
  })
}

// 导航守卫(路由钩子) - 路由的拦截器
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
